package router

import (
	"deliv-manage/handler"
	"deliv-manage/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Router() *gin.Engine {
	r := gin.Default()
	r.Use(Cors()) //默认跨域
	r.POST("/login", handler.Login)
	r.POST("/upload", MiddleWare(), handler.Upload)
	r.POST("role/roleNodeAdd", handler.RoleNodeAdd)  //角色与权限关联
	r.GET("user/userRoleList", handler.UserRoleList) //查询用户自身的角色
	r.GET("role/roleNodeList", handler.RoleNodeList) //查询角色的权限信息

	r.POST("person/personAdd", handler.PersonAdd)                //配送员添加
	r.POST("person/personOrderAdd", handler.PersonOrderAdd)      //订单添加
	r.GET("person/personOrderList", handler.PersonOrderList)     //查询角色的权限信息
	r.GET("person/personOrderDetail", handler.PersonOrderDetail) //订单详细信息展示
	return r
}

// 定义中间
func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("uid")
		if tokenString == "" {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "token为空",
			})
			c.Abort()
		}
		token, err := pkg.GetToken(tokenString)
		if err != "" {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "token验证失败",
			})
			c.Abort()
		}
		c.Set("uid", token["uid"])
		c.Next()
	}
}

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
